package net.awpspace.walkman.utils;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.VolumeControl;

import net.awpspace.walkman.entity.MP3;
import net.awpspace.walkman.view.Playing;

/**
 * MediaPlayer engine
 * 
 * @author Diep AwpSpace
 * 
 */
public class Engine implements PlayerListener {

	private final static String MP3_TYPE = "audio/mp3";

	private final static long SEEK_RATIO = 2000000; // 2 seconds

	private Player player;
	private VolumeControl volumeControl;

	public void playNoise() {
		try {
			if ((player != null) && (player.getState() == Player.PREFETCHED)) {
				player.start();
			}
		} catch (MediaException e) {
			e.printStackTrace();
		}
	}

	public void stopNoise() {
		try {
			if ((player != null) && (player.getState() == Player.STARTED)) {
				player.stop();
				player.setMediaTime(0);
			}
		} catch (MediaException e) {
			e.printStackTrace();
		}
	}

	public void pauseNoise() {
		try {
			if ((player != null) && (player.getState() == Player.STARTED)) {
				player.stop();
			}
		} catch (MediaException e) {
			e.printStackTrace();
		}
	}

	public synchronized void readNoise(MP3 mp3) {
		stopNoise();
		try {
			InputStream is = Connector.openInputStream(mp3.filePath);

			player = Manager.createPlayer(is, MP3_TYPE);
			player.addPlayerListener(this);
			player.realize();
			volumeControl = (VolumeControl) player.getControl("VolumeControl");
			setVolumeLevel(Playing.volume);
			player.prefetch();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MediaException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
	}

	public void setVolumeLevel(int level) {
		if (volumeControl != null) {
			volumeControl.setLevel(level * 10);
		}
	}

	public void seek(boolean isForwardSeek) {
		if ((player != null) && (player.getState() == Player.STARTED)) {

			try {
				long currentTime = player.getMediaTime();

				if (currentTime != Player.TIME_UNKNOWN) {
					if (isForwardSeek)
						currentTime += SEEK_RATIO;
					else
						currentTime -= SEEK_RATIO;
					player.setMediaTime(currentTime);
				}
			} catch (MediaException e) {
				// unable to change current time in a song
				e.printStackTrace();
			}
		}
	}

	public void playerUpdate(Player player, String event, Object eventData) {

	}
}
